package com.hex.ds.em.hcdp.gauss.common.utils;

import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xddf.usermodel.chart.XDDFChartData;
import org.apache.poi.xddf.usermodel.chart.XDDFDataSource;
import org.apache.poi.xddf.usermodel.chart.XDDFDataSourcesFactory;
import org.apache.poi.xddf.usermodel.chart.XDDFNumericalDataSource;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xwpf.usermodel.XWPFChart;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.assertj.core.util.Strings;

/**
 * @author : ky.zhang
 * @description :
 * @createDate : 2024/8/29 11:25
 */
public class PoiUtil {
    public static XWPFChart wordExportChar(XWPFChart docChart, String title, String[] seriesNames, XSSFSheet sheet, int startRow, int endRow) {
        //获取图表数据对象
        XDDFChartData chartData = docChart.getChartSeries().get(0);

        //word图表均对应一个内置的excel，用于保存图表对应的数据
        //excel中 第一列第二行开始的数据为分类信息
        //CellRangeAddress(1, categories.size(), 0, 0) 四个参数依次为 起始行 截止行 起始列 截止列。
        //根据分类信息的范围创建分类信息的数据源
        XDDFDataSource<String> catDataSource = XDDFDataSourcesFactory.fromStringCellRange(sheet, new CellRangeAddress(startRow, endRow, 0, 0));
        //更新数据
        for (int i = 0; i < seriesNames.length; i++) {
            //excel中各系列对应的数据的范围
            //根据数据的范围创建值的数据源
            XDDFNumericalDataSource<Double> valDataSource = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(startRow, endRow, 1, 1));
            //获取图表系列的数据对象
            XDDFChartData.Series series = chartData.getSeries(i);
            //替换系列数据对象中的分类和值
            series.replaceData(catDataSource, valDataSource);
            //修改系列数据对象中的标题
            CellReference cellReference = docChart.setSheetTitle(seriesNames[i], 1);
            series.setTitle(seriesNames[i], cellReference);
        }
        //更新图表数据对象
        docChart.plot(chartData);
        //图表整体的标题 传空值则不替换标题
        if (!Strings.isNullOrEmpty(title)) {
            docChart.setTitleText(title);
            docChart.setTitleOverlay(false);
        }
        return docChart;
    }

    /**
     * 将word内的段落内容进行替换
     */
    public static XWPFDocument replaceTextInDocument(XWPFDocument doc, String textToReplace, String replacementText) {
        for (XWPFParagraph paragraph : doc.getParagraphs()) {
            for (XWPFRun run : paragraph.getRuns()) {
                String text = run.getText(0);
                if (text != null && text.contains(textToReplace)) {
                    text = text.replace(textToReplace, replacementText);
                    run.setText(text, 0);
                }
            }
        }
        return doc;
    }
}
